using System;
using UnityEngine;

namespace Framework.Cron
{
    public class Cron
    {
        private float Elapse { get; set; }
        private Action<object[]> Handler { get; set; }
        private CronType CronType { get; set; }

        private float LimitTime { get; set; }
        private float CurrentTime { get; set; }
        private bool Running { get; set; }
        private object[] Args { get; set; }

        public Cron(CronType type, float elapse, Action<object[]> handler, params object[] args)
        {
            CronType = type;
            Elapse = elapse;
            Handler = handler;
            Args = args;

            LimitTime = Time.deltaTime + Elapse;
            CurrentTime = Time.deltaTime;
            Running = true;
        }

        public void Reset()
        {
            Running = false;
            Handler = null;
        }

        public bool Update()
        {
            if (!Running)
                return true;
            
            CurrentTime += Time.deltaTime;
            if (CurrentTime >= LimitTime)
            {
                if (Handler != null)
                    Handler(Args);

                if (CronType == CronType.Every)
                {
                    CurrentTime -= Elapse;
                }
                else if (CronType == CronType.After)
                {
                    Running = false;
                    Handler = null;

                    return true;
                }
            }

            return false;
        }
    }
}
